// pages/map/my/my.js
const app = getApp();
const handler = require("../../../utils/function.js");
const data = require("../../../data/mockData.js");
var api = require("../../../api.js");
var siteinfo = require("../../../siteinfo.js");
const openId = wx.getStorageSync("openId");
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isOpen: false,
    user_info:{
      nickname:''
    },
    copyright:'',
    copyright_rule:'',
    avatar: "/images/user/icon-07.png",
    longitude: 108.93,
    latitude: 32.28,
    mapWidth: 100,
    markers: [{
      iconPath: "../../../images/icon/icon-20.png",
      id: 0,
      latitude: 32.27,
      longitude: 108.93,
      width: 20,
      height: 20
    }],
    polyline: [{
      points: [{
        longitude: 108.93,
        latitude: 32.28
      }, {
        longitude: 108.94,
        latitude: 32.27
      }],
      color: "#FF0000DD",
      width: 2,
      dottedLine: true
    }],
    controls: [{
      id: 1,
      iconPath: '../../../images/icon/icon-22.png',
      position: {
        left: 34,
        top: 33,
        width: 50,
        height: 50
      },
      clickable: true
    }
    ],
    scrollLeft: 0,
    zuoyou: "icon-zuoyou",
    avatar: "../../../images/icon/icon-07.png",
    buttonText: "一键授权登录",
    username: "未登录",
    is_login: false,
    button_loading: false,
    driver_text: "司机招募",
    driver_url: '../../driver/driverAgreement/driverAgreement',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 获取当前位置
    // console.log("my_page")
    this.getlocation();
    // 获取优惠券
    if (options.uid) {
      app.shareCouponsMessage(options.uid);
    }
	if (options.scene){
	  wx.setStorageSync('scene', options.scene);
	}
  },
  /**
   * scrollLeftHandler页面轮动
   * 
   */
  scrollLeftHandler: function () {
    if (this.data.scrollLeft === 0) {
      this.setData({ scrollLeft: -650, zuoyou: "icon-zuoyou1", mapWidth: 750 });
    } else {
      this.setData({ scrollLeft: 0, zuoyou: "icon-zuoyou", mapWidth: 100 });
    }
  },
  // 退出登录
  login_out() {
    // console.log("login_out");
    let that = this;
    wx.showModal({
      title: '温馨提示',
      content: '确定要退出当前账号吗',
      success (res) {
        if (res.confirm) {
          try {
            wx.clearStorageSync()
          } catch (e) {
      
          }
          that.setData({
            user_info: '',
            is_login: false
          })
          wx.showToast({
            title: '退出成功',
            icon: 'none',
            
          })
          setTimeout(() => {
            wx.navigateBack({
              delta: 1
            })
          }, 1000);
        } else if (res.cancel) {
          // console.log('用户点击取消')
        }
      }
    })
   

  },
  //司机招募
  driver_btn_func(e) {
    var formid = e.detail.formId
    app.PushfromId(formid)
    if (this.data.user_info.nickname == '') {
      app.showToast('请先登录', 0, 1000, () => {
        app.navTo('/pages/logs/logs')
      })
      // wx.showToast({
      //   title:'请先登录',
      //   icon:'none',

      // })
      return false;
    }
      // if(!this.data.user_info){
      //   wx.showToast({
      //     title: '请先登陆',
      //     icon: 'none',
      //   })
      //   return 
      // }
    if (!this.data.user_info.phone) {
      wx.navigateTo({
        url: '/pages/logs/logs',
      })
      return
    }
    let url = e.currentTarget.dataset.skip
    if (url == "shenhezhong") {
      wx.showToast({
        title: '资料审核中',
        icon: 'none',
        duration:5000
      })
      return;
    }
    if (url == "weitongguo") {
      // console.log(this.data.driver_btn_why)
      var why=this.data.driver_btn_why;
      wx.showModal({
        title: '提示',
        content: why,
      })
      return;
    }
    if (url == "chongxinshenghe"){
      wx.navigateTo({
        url: '/pages/driver/personalInformation/personalInformation',
      })
    }
    wx.navigateTo({
      url
    })
  },
  // 获取底部版权
  getcopyright(){
    let that = this;
    app.request({
      url: api.user.getcopyright,
      method: 'post',
      data: {
      },
      success: function (res) {
        // console.log(res.code)
        if (res.code == 1) {
          that.setData({
            copyright: res.data.copyright,
            copyright_rule: res.data.copyright_rule
          })
        } 
      }
    })
  },
  // 登陆成功后
  login_succ_func(user_info) {
    let that=this;
    // 获取待机人员申请状态接口
    let apply_status = new Promise((resolve,reject)=>{
      app.request({
        url: api.driver.getstatus,
        method: 'post',
        data: {
        },
        success: function (rs) {
          if(rs.code==1){
            //type 1 代驾 0 用户
            wx.setStorageSync("usertype", rs.data.type )
            that.setData({ serverPhone: rs.data.serverphone})
            resolve(rs.data)
          }else{
            wx.showToast({
              title: '申请状态获取失败',
              icon: 'none',
            })
          }
        }
      })
    })
    apply_status.then(data=>{
      let type = data.type;
      let audit = data.audit;
      let is_complete = data.is_complete;
      let is_margin = data.is_margin;
      let applyfor = data.applyfor;
      //applyfor=2;
      //applyfor 1不可以发起重新申请 2正常可以发起重新申请
      // type  0-->用户  1-->司机
      // audit  0-->审核中  1-->审核通过  2-->拒绝通过
      //is_margin 0 未交保证金 1已交保证金 2 已退款
      // is_complete 0信息未完善 1信息已完善
      if (type ==1){
        // 司机身份
        if (is_complete==1){
          // 信息已完善
          audit = audit + "";

          switch (audit) {
            case "0":
              this.setData({
                driver_btn: {
                  text: '审核中',
                  url: 'shenhezhong'
                }
              })
              break;
            case "1":
              if (is_margin==1){
                // 跳转司机首页
                this.setData({
                  driver_btn: {
                    text: '司机入口',
                    url: '/pages/index/index'
                  }
                })
              }else{
                // 跳转缴纳保证金页面
                this.setData({
                  driver_btn: {
                    text: '交纳保证金',
                    url: '/pages/driver/userauth-pay/index'
                  }
                })
              }
              break;
            case "2":
              if (applyfor==1){
                this.setData({
                  driver_btn: {
                    text: '司机招募',
                    url: 'weitongguo'
                  },
                  driver_btn_why: data.why
                })
              }else{
                this.setData({
                  driver_btn: {
                    text: '重新审核',
                    url: 'chongxinshenghe'
                  },
                })
              }
              
              break;
            default:
              break;
          }
        }else{
          // 信息未完善
          this.setData({
            driver_btn: {
              text: '完善司机信息',
              url: '/pages/driver/personalInformation/personalInformation'
            }
          })
           // 更改 完善司机信息 页面路径-----------------------------------------------------------------------------------
        }
      }else{
        // 普通用户
        this.setData({
          driver_btn: {
            text: '司机招募',
            url: '/pages/driver/driverAgreement/driverAgreement'
          }
        })
      }
    })
    
    this.setData({
      is_login: true,
      user_info: user_info,
      button_loading: false
    })
    return;
  },
  /**loginHandler用户登录页面 */
  loginHandler: function (e) {
    wx.removeStorageSync("access_token");
    let that = this;
    wx.showLoading()
    this.setData({
      button_loading: true
    })
    wx.login({
      success: res1 => {
        // console.log(res1);
        if (res1.code) {
          wx.getUserInfo({
            success: res => {
              // console.log(res);
              wx.hideLoading()
              app.request({
                url: api.user.login,
                method: 'post',
                data: {
                  code: res1.code,
                  iv: res.iv,
                  encryptedData: res.encryptedData
                },
                success: function (rs) {
                  //获取到用户详细信息
                  // console.log(rs);
                  if (rs.code == 1) {
                    wx.showToast({
                      title: '登录成功',
                      icon: 'success',
                      duration: 2000
                    })
                    wx.setStorageSync("user_info", rs.data)
                    wx.setStorageSync("access_token", rs.data.access_token)
                    that.login_succ_func(rs.data)
                  } else {
                    wx.removeStorage({
                      key: 'access_token',
                    })
                    wx.showToast({
                      title: '登录失败',
                      icon: 'none',
                      duration: 2000
                    })
                  }
                },
              })
            }
          })
        }
      }
    })
  },
  relstiveServerHandler: function () {
    handler.callPhoneHandler(this.data.serverPhone);
  },
  navTo(e){
    console.log(e, e.currentTarget.dataset.url);
    app.navTo(e.currentTarget.dataset.url)
  },
  // intoPageHandler 页面跳转
  intoPageHandler: function (e) {
    // console.log(e.currentTarget.dataset.skip);
    var formid=e.detail.formId
    app.PushfromId(formid)
    // 判断是否登录
    if (this.data.user_info.nickname == ''){
      app.showToast('请先登录',0,1000,()=>{
        console.log("未登录数据");
        app.navTo('/pages/logs/logs') 
      })
      // wx.showToast({
      //   title:'请先登录',
      //   icon:'none',
        
      // })
      return false;
    }

    // 判断是否绑定手机号
    if (!this.data.user_info.phone) {
      wx.navigateTo({
        url: '/pages/logs/logs'
      })
      return;
    }

    // 判断是否点击的是 进行中  如果是 获取当前进行中的订单ID 跳转
    if(e.currentTarget.dataset.skip=="../orderGoing/orderGoing"){
      // console.log("查询进行中订单");
      var that = this;
      app.request({
          url: api.order.order_list,
          method: 'post',
          data: {},
          success: function(rs) {
              //  console.log(rs);
               if(rs.code==1){
                  let list = rs.data.data;
                  let now_order = "";
                  list.forEach(e => {
                    if(e.is_service==1){
                      now_order  = e;
                    }
                  });
                 if (!now_order.order_no){
                   wx.showToast({
                     title: '暂无进行中订单',
                     icon: 'none',
                     mask:true
                   })
                   return false;
                 }
                  wx.navigateTo({
                    url:'../orderGoing/orderGoing?order_no='+now_order.order_no
                  })
               }else{
                wx.showToast({
                  title:rs.msg,
                  icon:'none',
                })
               }
          }
      })
      return;
    }
    // 判断分销身份
    if (e.currentTarget.dataset.skip == "../../distributionLogin/distributionLogin") {
      let that = this;
      app.request({
        url: api.user.distribution_state,
        method: 'post',
        data: {},
        success: function (res) {
          if (res.code == 0) {
            wx.showModal({
              title: res.msg,
              content: '是否申请成为分销商！',
              success(res) {
                if (res.confirm) {
                  wx.navigateTo({
                    url: '../../distributionLogin/distributionLogin',
                  })
                } else if (res.cancel) {
                  // console.log('用户点击取消')
                }
              }
            })
          } else if (res.code == 1) {
            wx.navigateTo({
              url: '../../distributionCenter/distributionCenter',
            })
          } else if (res.code == 2) {
            wx.showToast({
              title: res.msg,
              icon: 'none',
              duration: 2000
            })
          } else if (res.code == 3) {
            wx.showModal({
              title: '提示',
              content: res.msg + ',' + res.data.reason + ',是否重新申请成为分销商！',
              success(res) {
                if (res.confirm) {
                  wx.navigateTo({
                    url: '../../distributionLogin/distributionLogin',
                  })
                } else if (res.cancel) {
                  // console.log('用户点击取消')
                }
              }
            })
          } else if (res.code == 4) {
            wx.showToast({
              title: res.msg,
              icon: 'none',
              duration: 2000
            })
          } else {
            wx.showToast({
              title: res.msg,
              icon: 'none',
              duration: 2000
            })
          }
        }
      })
      return;
    }
    wx.navigateTo({
      url: e.currentTarget.dataset.skip,
    })
  },
  // callPhoneHandler 联系客服
  callPhoneHandler: function () {
    wx.makePhoneCall({
      phoneNumber: wx.getStorageSync("serverPhone"),
    })
  },
  // 获取地理位置
  getlocation: function () {
    const that = this;
    wx.getLocation({
      type: 'gcj02',
      success: function (res) {
        var latitude = res.latitude
        var longitude = res.longitude
        var speed = res.speed
        var accuracy = res.accuracy
        // console.log("latitude:" + latitude)
        // console.log("longitude:" + longitude)
        // console.log("speed:" + speed)
        // console.log("accuracy:" + accuracy)
        that.setData({ latitude, longitude });
        // wx.openLocation({
        //   latitude: latitude,
        //   longitude: longitude,
        //   scale: 28
        // })
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // 获取分销权限
    this.getJurisdiction();

    this.getcopyright()
    let user_info = wx.getStorageSync("user_info");
        if (user_info){
          // console.log(user_info)
          this.login_succ_func(user_info);
        }else{
          this.setData({
            driver_btn: {
              text: '司机招募',
              url: 'shenhezhong'
            }
          })
        }
  },
  getJurisdiction: function () {
    var that = this;
    app.request({
      url: api.distribution.plugs_list,
      method: 'post',
      data: {},
      success: function (res) {
        if (res.code == 1 && res.data.distribution.is_open == '1' && res.data.distribution.open_distribution == 1) {
          that.setData({
            isOpen: true
          })
        } else {
          that.setData({
            isOpen: false
          })
        }
      }
    })
  },
  scrollLeft: function (e) {
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },
  // 用户分享
  onShareAppMessage: function () {
    let title = app.shareAppMessage().title;
    let imageUrl = app.shareAppMessage().imageUrl;
    let desc = app.shareAppMessage().desc;
    let path = app.shareAppMessage().path;
    // console.log(app.shareAppMessage())
    return {
      title: title,
      imageUrl: imageUrl,
      desc: desc,
      path: path,
    }
  },
})